#include "model/manager.h"
#include "assertion.h"
#include "smart_serve_log.h"

namespace OHOS {
namespace SmartServe {

bool CheckAdapter(ModelAdapter* adapter)
{
    if (adapter->InitialResConfigs().empty()) {
        SMART_SERVE_LOGE("[ModelManager] Got empty InitialResConfigs for model %s", adapter->Name().c_str());
        return false;
    }

    return true;
}

Model* ModelManager::GetOrCreateModel(const std::string& name)
{
    auto it = allModels_.find(name);

    if (it == allModels_.end()) {
        // 创建新 Model
        auto mc = GetCreator(name);
        if (mc == nullptr) {
            return nullptr; // ErrorType::NOT_FOUND_ERROR, param "model", "Requested model not registered"
        }

        auto ma = mc->Create();
        if (ma == nullptr) {
            return nullptr;
        }
        if (!CheckAdapter(ma.get())) {
            ma->Finalize();
            return nullptr;
        }
        auto model = std::make_unique<Model>(std::move(ma));

        auto ret = allModels_.insert({name, std::move(model)});
        ASSERT(ret.second);
        it = ret.first;
    }

    return it->second.get();
}

} // namespace SmartServe
} // namespace OHOS
